<?php
namespace app\shop\controller;

use app\common\model\shop\CurrencyModel;
use app\common\model\shop\PlatformModel;
use app\common\model\shop\ShopsModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;

/**
 * 店铺管理
 * @package app\admin\controller
 * @author xuli
 * @DateTime 2024-10-29 14:10
 */
class Shop extends Controller
{
    /**
     * 店铺列表
     * @auth true
     * @menu true
     * @author xuli
     * @DateTime 2024-10-29 14:10
     * @return void
     */
    public function index()
    {
        $this->platform_id = $this->request->get('platform_id', 0);
        ShopsModel::mQuery()->layTable(function () {
            $this->title = lang('店铺管理');
            // 获取授权平台列表
            $this->platform_list = PlatformModel::mk()->where('status', 1)->select()->toArray();

            if($this->platform_id) {
                $this->platform_info = PlatformModel::mk()->find($this->platform_id);
            } else {
                $this->platform_info = current($this->platform_list);
                $this->platform_id = $this->platform_info['id'] ?? 0;
            }

            // 获取状态
            $this->status_list = ShopsModel::authStatus();

        }, function (QueryHelper $query) {
            $where = [
                ['is_deleted', '=', 0],
                ['platform_id', '=', $this->platform_id],
            ];
            $status = $this->request->get('status', '');
            if($status != '') {
                $where[] = ['status', '=', $status];
            }
            if(!$this->super){
                $this->check_user = true;
            }
            $query->where($where);
            // 数据列表搜索过滤
            $query->like('name#shop_name')->equal('is_deleted,status')->dateBetween('create_at');
        });
    }

    protected function _index_page_filter(&$data)
    {
        // 获取币种信息
        $currenct_ids = array_column($data, 'currency_id');
        $currenct_data = [];
        if(!empty($currenct_ids)){
            $currenct_data = CurrencyModel::mk()->whereIn('id', $currenct_ids)->column('currency_name', 'id');
        }
        foreach ($data as &$vo) {
            $vo['status_name'] = ShopsModel::authStatus()[$vo['status']] ?? '';
            $vo['currency_text'] = !empty($currenct_data[$vo['currency_id']]) ? $currenct_data[$vo['currency_id']] : '';
        }
    }

    /**
     * 添加
     * @auth true
     * @menu true
     * @return void
     */
     public function add()
     {
         $this->platform_id = $this->request->param('platform_id', 0);
         $this->platform_info = PlatformModel::mk()->find($this->platform_id);

         ShopsModel::mForm($this->platform_info['code'] . '_add');
     }

    /**
     * 编辑
     * @auth true
     * @menu true
     * @return void
     */
     public function edit()
     {
         $this->platform_id = $this->request->param('platform_id', 0);
         $this->platform_info = PlatformModel::mk()->find($this->platform_id);

         ShopsModel::mForm($this->platform_info['code'] . '_add');
     }

    protected function _form_filter(&$data)
    {
        $params = $this->request->param();
        if($this->request->isPost()) {

            $data = [
                'name' => $params['name'],
                'client_id' => $params['client_id'] ?? 0,
                'api_key' => $params['api_key'],
                'creater' => $this->adminUser['username'],
                'platform_id' => $params['platform_id'] ?? 0,
                'user_id' => $this->adminUser['id'],
                'currency_id'    => $params['currency_id']  ?? 0,
                'account_id'    => $params['account_id'] ?? 0,
            ];

            // 验证
            if($this->platform_info['code'] == 'ozon') {
                $this->_vali([
                    'name.require'        => lang('店铺名称不能为空'),
                    'name.length:1,100'   => lang('店铺名称长度不能超过100'),
                    'client_id.require'   => lang('client_id不能为空'),
                    'api_key.require'     => lang('api_key不能为空'),
                    'currency_id.require' => lang('币种不能为空'),
                    'account_id.require'  => lang('公司不能为空'),
                ]);
            }

            if(empty($params['id'])) { // 添加
                $result = ShopsModel::mk()->insertGetId($data);
            } else { // 编辑
                unset($data['user_id'], $data['creater'], $data['platform_id']);
                $data['updater'] = $this->adminUser['username'];
                $result = ShopsModel::mk()->where(['id' => $params['id']])->update($data);
            }

            if($result) {
                $this->success(lang('保存成功'));
            } else {
                $this->error(lang('保存失败'));
            }
        } else {
            $this->shop_account = !empty($data['account_id']) ? $data['account_id'] : $this->account_id;
        }
    }

    /**
     * 删除
     * @auth true
     * @menu true
     * @return void
     */
    public function delete()
    {
        $id = $this->request->param('id', 0);
        $info = ShopsModel::mk()->find($id);
        if(!$info) {
            $this->error('店铺信息错误');
        }
        try {
            $result = ShopsModel::where(['id' => $id])->update(['is_deleted' => 1]);
            if(!$result){
                throw new \Exception(lang('删除失败'));
            }
        } catch (\Exception $e) {
            $this->error(lang('删除失败'));
        }
        $this->success(lang('删除成功'));
    }


}